package com.itheima.goods.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.goods.pojo.Brand;
import com.itheima.goods.service.BrandService;
import entity.PageResult;
import entity.Result;
import entity.StatusCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/brand")
@CrossOrigin
public class BrandController {
    @Autowired
    BrandService brandService;

    @GetMapping()
    public Result findAll() {
        List<Brand> list = brandService.list();
        return new Result(true, StatusCode.OK, "查询成功", list);
    }

    @PostMapping()
    public Result add(@RequestBody Brand brand) {
        brandService.save(brand);
        return new Result(true, StatusCode.OK, "添加成功");
    }

    @GetMapping("search/{page}/{size}")
    public Result findPage(@PathVariable("page") Integer page,
                           @PathVariable("size") Integer size) {
        Page<Brand> pages = brandService.page(new Page<Brand>(page, size));
        PageResult<Brand> brandPageResult = new PageResult<>();
        brandPageResult.setTotal(pages.getTotal());
        brandPageResult.setRows(pages.getRecords());
        return new Result(true, StatusCode.OK, "查询成功", brandPageResult);
    }

    @PostMapping("search/{page}/{size}")
    public Result findPage(@PathVariable("page") Integer page,
                               @PathVariable("size") Integer size,
                               @RequestBody Map searchMap) {

        PageResult pageResult = brandService.findPage(page, size, searchMap);
        return new Result(true, StatusCode.OK, "查询成功", pageResult);
    }

    @GetMapping("/{id}")
    public Result findById(@PathVariable("id") Integer id) {
        Brand brand = brandService.getById(id);
        return new Result(true, StatusCode.OK, "查询成功", brand);
    }

    @PutMapping("/{id}")
    public Result update(@RequestBody Brand brand,
                         @PathVariable("id") Integer id) {
        LambdaQueryWrapper<Brand> wrapper = Wrappers.<Brand>lambdaQuery();
        wrapper.eq(Brand::getId, id);
        brandService.update(brand, wrapper);
        return new Result(true, StatusCode.OK, "修改成功");
    }

    @DeleteMapping("/{id}")
    public Result delete(@PathVariable("id") Integer id) {
        brandService.removeById(id);
        return new Result(true, StatusCode.OK, "删除成功");
    }
}
